package com.eco.utils;

import io.netty.channel.ChannelHandlerContext;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyCtxMap {
    private static final Logger log = LoggerFactory.getLogger(com.eco.utils.NettyCtxMap.class);

    private static Map<String, ChannelHandlerContext> map = new ConcurrentHashMap<>();

    public static void add(String clientId, ChannelHandlerContext ctx) {
        map.put(clientId, ctx);
        log.info("add连接通道[{}]成功", clientId);
    }

    public static void delByKey(String clientId) {
        map.remove(clientId);
        log.info("remove删除通道[{}]成功", clientId);
    }

    public static ChannelHandlerContext get(String clientId) {
        return map.get(clientId);
    }

    public static List<String> getKeys() {
        return new ArrayList<>(map.keySet());
    }

    public static String remove(ChannelHandlerContext ctx) {
        for (Map.Entry<String, ChannelHandlerContext> entry : map.entrySet()) {
            if (entry.getValue() == ctx) {
                map.remove(entry.getKey());
                return entry.getKey().toString();
            }
        }
        return null;
    }

    public static String get(ChannelHandlerContext ctx) {
        for (Map.Entry<String, ChannelHandlerContext> entry : map.entrySet()) {
            if (entry.getValue() == ctx)
            {
                return entry.getKey().toString();
            }
        }
        return null;
    }
}
